/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.modules.biz.service.impl;

import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.biz.domain.Incubator;
import me.zhengjie.modules.biz.domain.Lab;
import me.zhengjie.modules.biz.domain.Lock;
import me.zhengjie.modules.biz.domain.Opendoorrecord;
import me.zhengjie.modules.biz.repository.IncubatorRepository;
import me.zhengjie.modules.biz.repository.LabRepository;
import me.zhengjie.modules.biz.repository.LockRepository;
import me.zhengjie.modules.biz.repository.OpendoorrecordRepository;
import me.zhengjie.modules.biz.service.IncubatorService;
import me.zhengjie.modules.biz.service.dto.IncubatorDto;
import me.zhengjie.modules.biz.service.dto.IncubatorQueryCriteria;
import me.zhengjie.modules.biz.service.mapstruct.IncubatorMapper;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.utils.*;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Admin
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2023-02-17
 **/
@Service
@RequiredArgsConstructor
public class IncubatorServiceImpl implements IncubatorService {

    private final IncubatorRepository incubatorRepository;
    private final IncubatorMapper incubatorMapper;
    private final LabRepository labRepository;
    private final UserRepository userRepository;
    private final LockRepository lockRepository;
    private final OpendoorrecordRepository opendoorrecordRepository;

    @Override
    public Map<String, Object> queryAll(IncubatorQueryCriteria criteria, Pageable pageable) {
        Page<Incubator> page = incubatorRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<IncubatorDto> dto = page.map(incubatorMapper::toDto);
        List<IncubatorDto> resultDto = dto.getContent();
        for (IncubatorDto incubatorDto : resultDto) {
            Lab lab = labRepository.findById(incubatorDto.getLabId()).orElseGet(Lab::new);
            User user = userRepository.findById(Long.valueOf(incubatorDto.getAdministrator())).orElseGet(User::new);
            incubatorDto.setLabName(lab.getName());
            incubatorDto.setAdministratorName(user.getUsername());
        }
        return PageUtil.toPage(dto);
    }

    @Override
    public List<IncubatorDto> queryAll(IncubatorQueryCriteria criteria) {
        List<Incubator> incubatorList = incubatorRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder));
        List<IncubatorDto> incubatorDtoList = incubatorMapper.toDto(incubatorList);
        for (IncubatorDto incubatorDto : incubatorDtoList) {
            Lab lab = labRepository.findById(incubatorDto.getLabId()).orElseGet(Lab::new);
            User user = userRepository.findById(Long.valueOf(incubatorDto.getAdministrator())).orElseGet(User::new);
            incubatorDto.setLabName(lab.getName());
            incubatorDto.setAdministratorName(user.getUsername());
        }
        return incubatorDtoList;
    }

    @Override
    @Transactional
    public IncubatorDto findById(Integer id) {
        Incubator incubator = incubatorRepository.findById(id).orElseGet(Incubator::new);
        ValidationUtil.isNull(incubator.getId(), "Incubator", "id", id);
        return incubatorMapper.toDto(incubator);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public IncubatorDto create(Incubator resources) {
        resources.setIsOpen(0);
        IncubatorDto incubatorDto = incubatorMapper.toDto(incubatorRepository.save(resources));
        Lock lock = new Lock();
        lock.setIsOpen(0);
        lock.setCid(resources.getId());
        lock.setType(4);
        lock.setMac(resources.getMac());
        lockRepository.save(lock);
        return incubatorDto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Incubator resources) {
        Incubator incubator = incubatorRepository.findById(resources.getId()).orElseGet(Incubator::new);
        ValidationUtil.isNull(incubator.getId(), "Incubator", "id", resources.getId());
        incubator.copy(resources);
        Lock lock = lockRepository.findByCidType(resources.getId(), 4);
        if (lock != null) {
            lock.setMac(resources.getMac());
            lockRepository.save(lock);
        }
        incubatorRepository.save(incubator);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            Incubator incubator = incubatorRepository.findById(id).orElseGet(Incubator::new);
            incubatorRepository.deleteById(id);
            Lock lock = lockRepository.findByCidType(incubator.getId(), 4);
            if (lock != null) lockRepository.deleteById(lock.getId());
        }
    }

    @Override
    public void download(List<IncubatorDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (IncubatorDto incubator : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("名称", incubator.getName());
            map.put("实验室", incubator.getLabName());
            map.put("负责人", incubator.getAdministratorName());
            if (incubator.getTemperature() != null) {
                map.put("温度", incubator.getTemperature() + "℃");
            } else {
                map.put("温度", "--℃");
            }
            if (incubator.getTemperatureThresholdValue() != null) {
                map.put("温度阈值", incubator.getTemperatureThresholdValue() + "℃");
            } else {
                map.put("温度阈值", "--℃");
            }
            map.put("mac地址", incubator.getMac());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public void openDoor(Integer id) {
        Incubator incubator = incubatorRepository.findById(id).orElseGet(Incubator::new);

        incubator.setIsOpen(1);

        incubatorRepository.save(incubator);
        Lock lock = lockRepository.findByCidType(incubator.getId(), 4);

        if (lock == null) {
            lock = new Lock();
            lock.setType(4);
            lock.setCid(incubator.getId());
            lock.setMac("");
        }

        System.out.println(lock);
        lock.setIsOpen(1);
        lockRepository.save(lock);
    }

    @Override
    public void closeDoor(Integer id) {
        Incubator incubator = incubatorRepository.findById(id).orElseGet(Incubator::new);
        incubator.setIsOpen(0);
        incubatorRepository.save(incubator);
        Lock lock = lockRepository.findByCidType(incubator.getId(), 4);
        lock.setIsOpen(0);
        lockRepository.save(lock);
    }

    @Override
    public boolean setData(String mac, Float temperature, Float humidity) {
        Incubator incubator = incubatorRepository.findByMac(mac);
        if (incubator != null) {
            incubator.setTemperature(temperature);
//            cabinet.setHumidity(h * 100);
            incubatorRepository.save(incubator);
            return true;
        }

        return false;
    }
}
